package org.hydrakyoufeng.stuplatform.controller;

import org.hydrakyoufeng.stuplatform.exception.ProcessException;
import org.hydrakyoufeng.stuplatform.utils.ResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 方法参数校验异常
     * MethodArgumentNotValidException：springboot参数校验不通过时抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResultEntity<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("[全局异常处理] [参数校验不通过]{}", e.getMessage(), e);
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        ResultEntity resultEntity = ResultEntity.error(msg);
        return ResponseEntity.status(400).body(resultEntity);
    }

    /**
     * 全局异常处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResultEntity<String>> handleException(Exception e) {
        log.error("[全局异常处理] [发生异常]{}", e.getMessage(), e);
        ResultEntity resultEntity = ResultEntity.error("发生异常");
        return ResponseEntity.status(500).body(resultEntity);
    }

    /**
     * 自定义异常处理（业务逻辑异常）
     */
    @ExceptionHandler(ProcessException.class)
    public ResponseEntity<ResultEntity<String>> handleException(ProcessException e) {
        log.error("[全局异常处理] [发生异常]{}", e.getMessage(), e);
        ResultEntity resultEntity = ResultEntity.error(e.getMessage());
        return ResponseEntity.status(400).body(resultEntity);
    }
}
